<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身新会员档案生成</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <h3>生成新的会员</h3>
    <hr>
    <div class="form-row" >
        <h4 style="color:brown;width:150px;" >· 关联的体验课会员 </h4>
        <input id='trialCusNameInput' style="width:60px;" oninput="handletrialCusNameInput()" onclick="handletrialCusNameInput()">       
        <div id="trialResultList"></div>    
    </div>

    <div  class="form-row" >
        <h4 style="width:150px;">· 输入新会员的姓名</h4>
        <input type="text" id="cusName" style="width: 60px;" >       
    </div>

    
    <div id="insCheckBlock" class="form-row" ><h4>· 主管教练</h4> </div> 
    <div id="insCheckBox" class="form-row" style="width:300px;margin-left:20px;font-size:12px;" ></div>

    <div id="sex" class="form-row" style="width:250px;margin-top:10px;">
        <h4 style="width:100px;">· 会员性别</h4> 
            <input type="radio"  name="gender" value="男" >男<span style="margin-right:30px;"></span>
            
            <input type="radio"  name="gender" value="女" checked>女    
    </div>

    <div class="form-row">
        <h4><label for="dateInput" >· 会员生日</label></h4>     <input id="dateInput" type="date" style="width:120px;">    
    </div>
    <div class="form-row">
        <h4><label for="mobilePhone" >· 会员手机号</label></h4> <input type="text" id="mobilePhone" style="width:120px;" oninput="checkMobileValid()">
        <span id="mobileValidResult" style="display:inline; color:rgb(221, 126, 123)"></span>
    </div>

    <div class="form-row">
        <h4><label for='industrySelect'>· 会员行业 </label></h4> <select id="industrySelect"></select>
    </div>

    <div class="form-row">
        <h4>· 会员职业  </h4>   <select id="occuSelect"></select>     
    </div>

    <div class="form-row">
        <h4>· 会员来源  </h4>     
        <select id="cusSource"></select>
    </div>

    <div class="form-row">
        <h4>· 紧急联系人  </h4>     
        <input type="text" id="emergencyContact" style="width: 100px;" > 
    </div>

    <div class="form-row">
        <h4 style="font-size:12px;"><label for="mobilePhoneEmgc" >· 紧急联系人电话</label></h4> <input type="text" id="mobilePhoneEmgc" style="width:120px;" oninput="checkMobileValidEM()">
        <span id="mobilePhoneEmgcResult" style="display:inline; color:rgb(221, 126, 123)"></span>  
    </div>

    <div class="form-row">
        <h4>· 住址  </h4>     
        <textarea id="addr" style='width:120px;height: 60px;'></textarea>
    </div>

    <div class="form-row" style="margin-top:10px;">
        <h4>· 备注  </h4>     
        <textarea id="cmt" style='width:120px;height: 40px;'></textarea>
    </div>

    <div class="form-row">
               <h4 style="width:150px;">· 体验客户有效期 </h4>
            <input type="radio" name="trailPeriod" value="all">全部<span style="margin-right:30px;"></span>
            <input type="radio" name="trailPeriod" value="latest2" checked>近2个月
    </div>
    <hr>
    <div class="inline2" id="new_cus_res"></div>
    <div style="margin-top:8px;"><button onclick="generateFile()">生成会员资料</button></div>

    <script src="../static/js/common.js"></script>
    <script>
        let allTrialList;
        let insName;
        let insId;
        let insRole;
        let tmplt_info;

        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();
            selectToday();

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;
                // console.log(data)    
                generateCusSource(data['cus_source'])            
                  })
                .catch(error => console.error('Error:', error));

            fetch('./get_industry_occu')
            .then(response=>response.json())
            .then(data=>{
                console.log(data);
                generateIndOcc(ind_occ_data=data);
            })
            .catch(error=>{
                console.log('获取行业职业列表错误：',error);
            })

            fetch('/get_trial_list')
            .then(response=>response.json())
            .then(data=>{
                // console.log(data)
                allTrialList=data;
                // generateTrialCusList(data);
                
            })
            .catch(error=>{
                console.log('获取体验课列表错误：',error)
            });

            fetch('/get_ins_list', {
                method: 'GET',
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);
                generateInsCheckBoxes(data['ins_list']);
   
                 })
                .catch(error => console.error('Error:', error));

            hideTrialResultList();

            const trialCusNameInput=document.getElementById("trialCusNameInput");
            trialCusNameInput.addEventListener("click", function(event) {
                event.stopPropagation();
            });

            insInfo=hideInsSelectBlockAndGetInsInfo('insCheckBlock');
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不允许进入该页面，返回Index
            // if(insRole==='ins'){
            //     window.location.replace('./index');
            // }


        });

        function generateCusSource(data){
            const cusSrcSel=document.getElementById('cusSource');
            data.forEach(item=>{
                const opt=document.createElement('option');
                opt.value=item[0];
                opt.text=item[0];
                cusSrcSel.appendChild(opt);
            });
        }


        function generateIndOcc(ind_occ_data){
            const indSel=document.getElementById('industrySelect');
            const occSel=document.getElementById('occuSelect');

            const indData=ind_occ_data['industries'];
            const occData=ind_occ_data['occus'];

            indData.forEach(ind=>{
                const indOpt=document.createElement('option');
                indOpt.value=ind[0];
                indOpt.text=ind[1];
                indSel.appendChild(indOpt);
            });

            occData.forEach(occ=>{
                const occOpt=document.createElement('option');
                occOpt.value=occ[0];
                occOpt.text=occ[1];
                occSel.appendChild(occOpt);
            });

            indSel.addEventListener('change',function(){
                //如果是学生，则职业不给选，强制为“学生”
                if(indSel.value==='INT010'){
                    occSel.value='OCC03';
                    occSel.disabled=true;
                }else{
                    occSel.value='OCC01';
                    occSel.disabled=false;
                }        
            });

        }

        function generateInsCheckBoxes(insData){
            const insCheckBox=document.getElementById('insCheckBox');
            let firstCheck=true;
            insData.forEach(ins=>{ 
                // console.log(ins,insName)
                const checkbox=document.createElement('input')
                checkbox.type='checkbox';
                checkbox.name='check-option';
                checkbox.id='checkBox-'+ins.slice(0,8);
                checkbox.value=ins.slice(0,8);   
                if(insRole==='ins'){
                    if(insId===ins.slice(0,8)){
                        checkbox.checked=true;  
                    }
                }else if(insRole==='admin'){
                    if(firstCheck){
                        checkbox.checked=true;         
                        firstCheck=false;       
                    }   
                }               
                
                const label=document.createElement('label');
                label.htmlFor='checkBox-'+ins.slice(0,8);
                label.appendChild(checkbox);                 
                label.appendChild(document.createTextNode(ins.slice(8,)));       
                insCheckBox.append(label);                   
            });                
                
        }

            //在此页面重写该方法 
        function hideInsSelectBlockAndGetInsInfo(id){
                const sessionInsId=document.getElementById('sessionInsId').textContent;
                const sessionInsName=document.getElementById('sessionInsName').textContent;
                const sessionInsRole=document.getElementById('sessionInsRole').textContent;
                const insSelectBlock=document.getElementById(id);
                // if(sessionInsRole==='admin'){
                //     insSelectBlock.style.display='block';
                // }else if(sessionInsRole==='ins'){
                //     insSelectBlock.style.display='none';
                // }
  
                if(sessionInsRole==='admin'){   
                    // document.getElementById('insCheckBlock').style.display='block';
                    showRole.innerText='管理员'
                }else if(sessionInsRole==='ins'){ 
                    // document.getElementById('insCheckBlock').style.display='none';
                    showRole.innerText='教练'
                }
                
                const sessionRoleBlock=document.getElementById('sessionInsRole');
                sessionRoleBlock.style.display='none';



                return ({'sessionInsId':sessionInsId,'sessionInsName':sessionInsName,'sessionInsRole':sessionInsRole})
            }
        
        function checkMobileValid(){
            const mobilePattern = /^1[3-9]\d{9}$/;
            const mobile=document.getElementById('mobilePhone').value;
            const mobileValidResult=document.getElementById('mobileValidResult');
            mobileValidResult.innerText='';
            if(mobile && mobile!==''){
                if(!mobilePattern.test(mobile)){
                    mobileValidResult.innerText='无效的手机号码'
                }

            }
        }

        function checkMobileValidEM(){
            const mobilePattern = /^1[3-9]\d{9}$/;
            const mobile=document.getElementById('mobilePhoneEmgc').value;
            const mobileValidResult=document.getElementById('mobilePhoneEmgcResult');
            mobileValidResult.innerText='';
            if(mobile && mobile!==''){
                if(!mobilePattern.test(mobile)){
                    mobileValidResult.innerText='无效的手机号码'
                }

            }
        }

        function hideTrialResultList(){
            document.addEventListener('click',function(){
                const trialResultList=document.getElementById('trialResultList');
                trialResultList.style.display='none';
            });           
        }

        function handletrialCusNameInput() {
            
            
            // 获取输入框中的值
            const trialCusNameInput=document.getElementById("trialCusNameInput");
            const searchTerm = document.getElementById("trialCusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            const resultList=document.getElementById('trialResultList')

            trialCusNameInput.addEventListener("click", function(event) {
                event.stopPropagation();
            });

            // 清空列表
            resultList.style.display = "block";
            resultList.innerHTML = "";
            document.getElementById("cusSource").disabled=false;
            
            // if (UpperSearchTerm === "") {
            //     // resultList.style.display = "none";
            //     resultList.style.display = "block";
            //     return; // 输入框为空，不做处理
            // }else{
            //     resultList.style.display = "block";

            // }

            const trialCusList=generateTrialCusList();
            // console.log(trialCusList)
            
            
            // 遍历给定的数组，进行模糊匹配。倒序
            trialCusList.reverse().forEach(function(item) {
           
                if (item['体验客户姓名'].includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = item['体验客户姓名'];

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function(event) {
                        event.stopPropagation();
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("trialCusNameInput").value = item['体验客户姓名'];
                        document.getElementById("cusName").value = item['体验客户姓名'];  
                        document.getElementById('dateInput').value=dateToString(item['体验客户生日'],'date');
                        if(item['客户来源'] && item['客户来源']!==''){
                            document.getElementById("cusSource").value=item['客户来源'];
                            document.getElementById("mobilePhone").value=item['体验客户手机'];
                            document.getElementById("cusSource").disabled=true;
                        }else{
                            document.getElementById("cusSource").disabled=false;
                        }
                             

                        resultList.style.display = "none";
                        // getBuyList(item);
                        
                        // 手动触发change事件
                        // itemInput.dispatchEvent(new Event('change'));
                        // 清空结果列表

                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                    resultList.classList.add('cus-list-result-overflow');
                }
            });
        
            // resultList.classList.add("cus-list");
            
        }

        function generateTrialCusList(){
            // if(!data){
            //     data=allTrialList;
            // }
            // console.log(data['all_trial'])
            data=allTrialList;
            const trialRecs=Object.values(data['all_trial'])
            let latestTwoMonthList=[]
            trialRecs.forEach(trialRec=>{
                const compareDate=new Date()-new Date(trialRec['体验课日期']);
                const daysDifference = Math.floor(compareDate / 86400000);
                if(daysDifference<=60){
                    latestTwoMonthList.push(trialRec);
                }
            })
            // console.log('近2个月记录：',latestTwoMonthList)

            const trialCusPeriodRadio=document.querySelector('input[name="trailPeriod"]:checked').value;
            if(trialCusPeriodRadio==='latest2'){
                return latestTwoMonthList;
            }else{
                return Object.keys(data['all_trial']).map(key => data['all_trial'][key]);
            }

            
            

        }

        function selectToday(){
            const today = new Date();
            // 将日期格式化为 yyyy-mm-dd 的形式
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const date=String(today.getDate()).padStart(2, '0');

            const formattedDate = `${year}-${month}-${date}`;
            // console.log(formattedDate)

            // 将日期设置为输入框的默认值
            document.getElementById('dateInput').value = formattedDate;
        }

        function CheckAndGenerateFile() {            
            document.getElementById("new_cus_res").innerText=''
            const cusName=document.getElementById("cusName").value.trim();
            const gender=document.querySelector('input[name="gender"]:checked').value;
            const trailCusName=document.getElementById("trialCusNameInput").value.trim();
            const cusSource=document.getElementById("cusSource").value.trim();
            console.log('客户来源：',cusSource)

            let birthMonth=document.getElementById("dateMonth").value
            birthMonth=birthMonth.replace(/-/g,'');
            // console.log(gender,birthMonth);
            if(cusName){
                fetch('/check_new', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain'
                    },
                    body: 'checking'
                })
                .then(response => response.text())
                .then(Num => {
                    // 在这里处理后端返回的数据，例如给出成功提示
                    console.log('new_code:',Num)
                    var confirmRes=confirm("现在的序号是 MH"+Num+cusName+' ，如需修改序号请按【取消】修改。')
                    if (confirmRes){
                        generateFile(Num+cusName,trailCusName,gender,birthMonth,cusSource);
                    }else{
                        var newNum = prompt("请输入序号（三位数字）：");
                        const ptn=/^\d{3}$/;
                        while (!ptn.test(newNum)){   
                            if(newNum==='不输入' || newNum==='取消' ){
                                throw new Error('工作人员取消输入');
                                break;
                            }else{
                                newNum = prompt("输入的不是三位数字，请重新请输入。");   
                            }                        
                        }
                        generateFile(cusName,trailCusName,gender,birthMonth,cusSource);  
                        
                    }
                
                })
                .catch(error => {
                    alert(error);
                    console.error('Error:', error)});
            }else{
                alert('未输入姓名')
            }

        }

        function generateFile(){
            document.getElementById("new_cus_res").innerText=''
            const cusName=document.getElementById("cusName").value.trim();
            const gender=document.querySelector('input[name="gender"]:checked').value;
            const trialCusName=document.getElementById("trialCusNameInput").value.trim();
            const cusSource=document.getElementById("cusSource").value.trim();
            const mobilePhone=document.getElementById("mobilePhone").value.trim();
            const insNamesChecked=document.querySelectorAll('input[name="check-option"]:checked');
            const industry=document.getElementById("industrySelect").value;
            const occu=document.getElementById("occuSelect").value;
            const emgcContact=document.getElementById("emergencyContact").value.trim();
            const mobilePhoneEmgc=document.getElementById("mobilePhoneEmgc").value.trim();
            const addr=document.getElementById("addr").value.trim();
            const cmt=document.getElementById("cmt").value.trim();
            const addDateTime=dateToString(new Date(),'dateTime');

            insIdsList=[]
            insNamesChecked.forEach(checkedName=>{
                insIdsList.push(checkedName.value);
            })
            insIdsStr=insIdsList.join(',')        
            // console.log(insNamesStr)  

            let birthDay=document.getElementById("dateInput").value
            //18以下的需要确认生日
            if(new Date().getFullYear()-parseInt(birthDay.slice(0,4))<18){
                const confirmedDate=confirm(`请确认新会员生日：${birthDay}`);
                if(!confirmedDate){
                    return;
                }
            }
            
            birthDay=birthDay.replace(/-/g,'');

            if(cusName && insIdsStr){
                const isMo=isMobile();
                dvc=isMo?"mobile":"pc";
                document.getElementById("new_cus_res").innerHTML='<p>正在生成新会员……</p>'
                data={
                    'cusName':cusName,
                    'trialCusName':trialCusName,
                    'gender':gender,
                    'mobilePhone':mobilePhone,
                    'birthDay':birthDay,
                    'cusSource':cusSource,
                    'dvc':dvc,
                    'insIds':insIdsStr,
                    'industry_id':industry,
                    'occu_id':occu,
                    'emgc_contact':emgcContact,
                    'emgc_mobile':mobilePhoneEmgc,
                    'addr':addr,
                    'cmt':cmt,
                    'add_datetime':addDateTime
                }
                console.log(data)
                fetch('/generate_new',{
                    method:"POST",
                    headers:{
                        'Content-Type': 'application/json',
                    },
                    body:JSON.stringify(data)
                })
                .then(response=>response.json())
                .then(data=>{
                    console.log(data)
                    // document.getElementById("new_cus_res").innerHTML='<p>生成文件名：</p><p>'+data+'</p>'
                    if(data.res==='ok'){
                        alert(`新增客户 ${data.cus_name} 成功`);
                    }else{
                        console.log(data.error);
                        alert(`新增客户 ${data.error} 错误`);                        
                    }
                    
                    window.location.replace('./index');
                    // alert(data)
                })
                .catch(error=>console.error('Error:',error));
            }else{
                document.getElementById('new_cus_res').innerText='有空项，请检查。'
            }
            
        }

        function isMobile(){
            const userAgent = navigator.userAgent.toLowerCase();
            return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
        }


    </script>
</body>
</html>
